<template>
  <div class="order-count">
    <el-card shadow="never" class="card-com">
      <div class="card-1">
        <searchPanel @refresh="getData('reset')" >
          <!-- 查询面板 -->
          <template v-slot:search>
            <el-form :inline="true" :model="listSearch" class="demo-form-inline" label-width="120px">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="产品名称">
                    <el-select multiple v-model="listSearch.condition.productCodeList" style="width:100%"
                      @change="getData('search')" placeholder="请选择产品名称" filterable clearable collapse-tags
                      collapse-tags-tooltip>
                      <el-option v-for="item in listCollect.productList" :key="item.id" :value="item.key"
                        :label="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="渠道Key">
                    <ChannelSelect v-model:select-value="listSearch.condition.channelCodeList" :multiple="true"
                    @my-change="getData('search')"></ChannelSelect>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="时间">

                    <TimePicker v-model:operateTime="value1" style="width: 100%;" @timeChange="pickerChange">
                    </TimePicker>
                  </el-form-item>
                </el-col>


              </el-row>
              <el-row justify="end">
                <el-button type="primary" @click="getData('search')">查询</el-button>
                <el-button @click="getData('reset')">重置</el-button>
              </el-row>
            </el-form>
          </template>
          <!-- 字段添加 -->
          <template v-slot:edit>


            <el-dropdown :hide-on-click="false" style="margin: 0 10px;" trigger="click">
              <el-button title="过滤表头">
                <el-icon :size="18">
                  <Grid />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-checkbox-group v-model="selectTitle" size="small" @change="checkboxChange">
                    <el-dropdown-item v-for="item in showTitle" :key="item.prop">
                      <el-checkbox :label="item.label" :value="item.prop" />
                    </el-dropdown-item>
                  </el-checkbox-group>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </searchPanel>
      </div>
      <div class="card-2">
        <OnlyTable ref="onlyTableRef" class="card-2" :tableProps="tableProp" :pageTotal="pageParams.total" @get-page="handPage"
          :tableData="pageParams.tableData" :tableHeight="pageParams.tableHeight" :loading="pageParams.loadIng">
          <template #userVisit="scope">
            <div style="font-size: 15px; font-weight: 600;color: #000;">{{ scope.row?.userVisit }} </div>
            <div>
              <span style="color: #D0D0D0;">较昨日 </span>
              <span
                :style="{ color: Number(scope.row?.userVisit - scope.row?.yesterdayUserVisit) >= 0 ? 'red' : '#0FEE0F' }"
                style="font-size: 15px; font-weight: 600;">{{
                  titleSty(scope.row.userVisit, scope.row.yesterdayUserVisit) }} </span>
            </div>
          </template>
          <template #signingRate="scope">
            <div style="font-size: 15px; font-weight: 600;color: #000;">
              {{ scope.row?.signingRate }} %
            </div>
            <div>
              <span style="color: #D0D0D0;">较昨日 </span>
              <span
                :style="{ color: Number(scope.row?.signingRate - scope.row?.yesterdaySigningRate) >= 0 ? 'red' : '#0FEE0F' }"
                style="font-size: 15px; font-weight: 600;">{{
                  titleSty1(scope.row?.signingRate, scope.row?.yesterdaySigningRate) }} %</span>

            </div>
          </template>
        </OnlyTable>
      </div>
    </el-card>
    <downList ref="downListRef" @flash="btnDownList"></downList>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted, nextTick, defineAsyncComponent, onUnmounted } from "vue";
import { ElMessage } from "element-plus"
import _ from "lodash"
import { getProductStatisticsPage, getProductListAll, getExportInventoryPackageProductStatisticsPost } from "@/api/product";
import { channelListApiPost } from "@/api/userMangement";
import { Search, Plus, Refresh, Bottom, Link } from "@element-plus/icons-vue";
import useInstance from "@/hooks/useInstance";
import { getTodayStartAndEndTime } from "@/utils/index"
import { storeToRefs } from "pinia";
import { orderListStore } from "./pageStore"
import TimePicker from "@/components/customSon/timePicker.vue";

import { useComListData } from "@/store/list";
import mittBus from '@/utils/mitt';
/******************************************data****************************************** */

const {listCollect,getProListAll} = useComListData()
const { tableProp } = storeToRefs(orderListStore())
const selectTitle = ref<any>([])
const onlyTableRef=ref()
const downList = defineAsyncComponent(() => import("@/components/downList.vue"))
const downListRef = ref<{ show: (title: string, row?: any) => void }>()
const listSearch = reactive({
  orders: ["created_time desc","user_visit desc"],
  condition: {
    statisticsDateStart: null as any,
    statisticsDateEnd: null as any,
    channelCodeList: [],
    productCodeList: [],
  },
  pageSize: 20,
  pageNum: 1,
});

const pageParams = reactive({
  tableHeight: 400,
  total: 0,
  loadIng: false,
  tableData: [],

});
const value1 = ref<any>([]);
/******************************************method****************************************** */

onMounted(() => {
  selectTitle.value = tableProp.value.propsList.filter(it => it.hidden && it.label != "操作").map(item => item.prop)

  const { startOfDay, endOfDay } = getTodayStartAndEndTime()
  value1.value.push(startOfDay)
  value1.value.push(endOfDay)
  listSearch.condition.statisticsDateStart = startOfDay
  listSearch.condition.statisticsDateEnd = endOfDay
  getData("search");


  getProListAll({})

});
const checkboxChange = (val: string[]) => {
  pageParams.loadIng = true
  // 进入的 全部为 true 没有的为false
  tableProp.value.propsList = tableProp.value.propsList.map((item: any) => {

    if (val.includes(item.prop)) {
      return {
        ...item,
        hidden: true
      }
    } else if (item.label == "操作") {
      return {
        ...item,
        hidden: true
      }
    } else {
      return {
        ...item,
        hidden: false
      }
    }
  })
  pageParams.loadIng = false
}
const showTitle = computed(() => {
  return tableProp.value.propsList.filter(it => it.label != "操作")
})
const titleSty = (val1: any, val2: any) => {
  const result = val1 - val2
  if (result >= 0) {
    return `+ ${result}`
  } else {
    return `${result}`
  }
}
const titleSty1 = (val1:any, val2:any) => {

  return val2
}



const pickerChange = (time: any) => {
  if (time && time.length > 0) {
    listSearch.condition.statisticsDateStart = time[0];
    listSearch.condition.statisticsDateEnd = time[1];
  } else {
    listSearch.condition.statisticsDateStart = null;
    listSearch.condition.statisticsDateEnd = null;
  }
  getData('search')
};
const getData = async (type: string) => {
  pageParams.loadIng = true;

  try {
    if (type == "reset") {
      listSearch.pageNum = 1;
      listSearch.pageSize = 20;
      listSearch.condition.channelCodeList = [];
      listSearch.condition.productCodeList = [];
      listSearch.condition.statisticsDateStart = null;
      listSearch.condition.statisticsDateEnd = null;
      value1.value = null
      onlyTableRef.value.initPagination()
    }
    const res = await getProductStatisticsPage(listSearch);
    if (res.code == 20000) {
      // 处理数据
      pageParams.tableData = res.data.records;
      pageParams.loadIng = false;
      pageParams.total = res.data.total;
    }
    console.log(res.data);
  } catch (error) {
    pageParams.loadIng = false;
  }finally{
    mittBus.emit('scrollUpdate')
  }
};
const handleSizeChange = (size: number) => {
  listSearch.pageSize = size;

  getData("search");
};
const handleCurrentChange = (page: number) => {
  listSearch.pageNum = page;
  getData("search");
};
const handPage = (val: { pageNum: number; pageSize: number }) => {
  listSearch.pageNum = val.pageNum;
  listSearch.pageSize = val.pageSize;
  getData("search");
};
const btnDown = async () => {
  try {
    const res = await getExportInventoryPackageProductStatisticsPost({ condition: listSearch.condition })
    if (res.code == 20000) {
      ElMessage({
        type: "success",
        message: "下载成功 请查看下载列表 未出现下载数据 可等待在刷新下载列表！"
      })
    }
  } catch (error) {
    ElMessage({
      type: "error",
      message: "下载失败 请稍后再试！"
    })
  }

}
const btnDownList = () => {
  /**
   * CHANNEL( "channel", "渠道信息"),
PRODUCT( "product", "产品信息"),
INVENTORY_PACKAGE_ORDER( "inventoryPackageOrder", "存量包订单信息"),
INVENTORY_PACKAGE_PRODUCT_STATISTICS( "inventoryPackageProductStatistics", "存量包产品统计信息"),
   */
  downListRef.value?.show('存量包产品统计信息下载列表', 'inventoryPackageProductStatistics')
}
</script>

<style lang="scss" scoped>
.order-count {
  height: calc(100vh - 70px);

  .card-com {
    display: flex;
    flex-direction: column;
    // height: 100%;

    .card-2 {
      flex-grow: 1;
    }
  }
}
</style>